package com.dicsystems.myrec.dao;

import java.util.ArrayList;
import java.util.List;

import com.dicsystems.myrec.DatabaseHelper;
import com.dicsystems.myrec.dto.Image;
import com.dicsystems.myrec.dto.Todo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ImageDao {

	private Context me;
	private SQLiteDatabase db;
	private final String TABLE = "image";
	private final int ID = 0;
	private final int TODO_ID = 1;
	private final int PATH = 2;

	public ImageDao(Context context) {
		this.me = context;
	}

	public void open() {
		db = new DatabaseHelper(me).getReadableDatabase();
	}

	public void close() {
		db.close();
	}

	public void delete(Todo todo) {
		db.delete(TABLE, "todo_id = ?", new String[] {todo.id});
	}

	public List<Image> select(Todo todo) {
		List<Image> images = new ArrayList<Image>();
		Cursor cursor = db.query(TABLE, null, "todo_id = ?", new String[] {todo.id}, null, null, "_id");
		if(cursor.moveToFirst()) {
			do {
				Image image = new Image();
				image.id = cursor.getString(ID);
				image.todo_id = cursor.getString(TODO_ID);
				image.path = cursor.getString(PATH);
				images.add(image);
			} while(cursor.moveToNext());
		}
		cursor.close();
		return images;
	}

	public int count(Image image) {
		int count = 0;
		Cursor cursor = db.query(TABLE, null, "todo_id = ? AND path = ?", new String[] {image.todo_id, image.path}, null, null, null);
		if(cursor.moveToFirst()) {
			count = cursor.getCount();
		}
		cursor.close();
		return count;
	}
}
